#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data1 time : 2022/2/14   7:05 下午
# project   : export_Word_Auto.py
# IDE       : PyCharm
# email     :17600960626@163.com

import csv
import logging
import os
import re
import subprocess
import time


def r_csv(rows):
    #写入文件
    f = open("/Users/xm123/PycharmProjects/test_keyboard/Auto_Export/report/text.csv", 'a', encoding='utf-8', newline='')
    writer = csv.writer(f)
    writer.writerow(rows)
    f.close()


def word_dictionary():
    apk_name = []
    apk = {
        "ikey": "com.emoji.ikeyboard",
        "ikeyd": "com.emoji.ikeyboard.debug",
        "gb": "com.google.android.inputmethod.latin",
        "s": "com.touchtype.swiftkey",
        "touchpal": "com.cootek.smartinputv5",
        "facemoji": "com.simejikeyboard",
        "indic": "com.kikatech.keyboard.emoji.indian.debug",
        "oem": "com.kikaoem.hw.qisiemoji.inputmethod",
        "kika": "com.qisiemoji.inputmethod.debug",
        "huawei": "com.hw.inputmethod",
        "z": "com.huawei.ohos.inputmethod",
        "pro": "com.emoji.coolkeyboard",
        "prod": "com.emoji.coolkeyboard.debug",
        "prot": "kika.emoji.keyboard.teclados.clavier.debug",
        "xp": "com.kikatech.hackkeyboardxposedmodule",
        "prohw": "com.emoji.coolkeyboard.hw.store",
        "vivo": "com.kikaoem.vivo.qisiemoji.inputmethod",
        "hack": "com.kikatech.hackkeyboardxposedmodule"
    }
    apklist = input('请输入法简称，如："kiak输入：z","swk输入：s":')
    for key in apk:
        if key == apklist:
            apkname = apk[key]
            apk_name.append(apkname)
            logging.warning('输入法简称:%s ' % apkname)
            break
    else:
        print('输入法不存在，请重新选择')
        return word_dictionary()
    return apk_name


def connectDevice(Devicecmd):# 获取设备ip地址并连接
    '''
    初始化设备
    :param Devicecmd:cmd命令
    :return:
    '''
    device_str = subprocess.getoutput(Devicecmd)
    device_list = []
    m = (device_str.strip()).split('\n')
    for line in m[1:]:
        if 'List' not in line:
            device_list.append(line.split('\t')[0])
    print('已连接设备数量%s台'%len(device_list),"\n设备devicesID列表:",device_list)
    return device_list



def out_input(deviceslist):
    '''
    :param deviceslist: device列表
    :return:
    '''
    equipment_name=connectDevice(deviceslist)
    # apk_name = word_dictionary()
    for i in equipment_name:
        # for apk in apk_name:
        unins = 'adb -s %s shell su -c ls -l /sdcard/ | grep word_correct_report'%(i)
        # 获取word文件时间
        res = subprocess.Popen(unins, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                  universal_newlines=True)
        datetime=res.communicate()[0]
        mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})", datetime)#获取out_info时间
        print('工程执行完成后的时间是：%s'%mat.group())
        out_info = []
        out_info.append(mat.group())
        input_name = (input('输入导出文件的备注：').split())
        r_csv(out_info + input_name)

        date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})", datetime)
        for j in input_name:
            for item in date_all:
                # cmd = 'adb -s %s shell su -c cp /data/data/%s/files/word_output /sdcard/word_output' % (i, apk)
                pull = 'adb -s %s pull /sdcard/word_correct_report  /Users/xm123/Documents/The_script/word_output%s.csv'%(i,"-"+item+"-"+j)
            # pull出文件到本地
            #     subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
            #                      universal_newlines=True)
                print('将在8s内导出完成，请等待…………！')
                time.sleep(8)
                subprocess.Popen(pull, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                        universal_newlines=True)
                # print(word.stdout.read())
                logging.warning('导出完成！')
                # return out_info
    else:
        return out_input


if __name__ == '__main__':
    out_input('adb devices')
